//
//  LanguageViewController.m
//  LightControl
//
//  Created by CKF on 2025/8/8.
//

#import "LanguageViewController.h"
#import "ArrowView.h"
#import "DAConfig.h"
#import "NSBundle+DAUtils.h"
#import "TabbarController.h"
#import "SettingViewController.h"
@interface LanguageViewController ()
@property (nonatomic, strong) UILabel *languageLabel;
@property (nonatomic, strong) ArrowView *arrowView;
@end

@implementation LanguageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = LocalString(@"语言");
    self.view.backgroundColor = [UIColor whiteColor];
    [self creatUI];
}

-(void)creatUI{
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 60, 150, 30)];
    titleLabel.text = LocalString(@"选择语言");
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.textColor = [UIColor blackColor];
    [self.view addSubview:titleLabel];
    
    UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(KScreenWidth-54, 63, 24, 24)];
    imgView.image = [UIImage imageNamed:@"Translate"];
    [self.view addSubview:imgView];
    
    _languageLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 130, 150, 30)];
    _languageLabel.text = [[DAConfig userLanguage]isEqualToString:@"en"]?@"en":@"zh"; //en
    _languageLabel.font = [UIFont systemFontOfSize:17];
    _languageLabel.textColor = [UIColor blackColor];
    [self.view addSubview:_languageLabel];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(_languageLabel.frame)+10, KScreenWidth-60, 2)];
    line.backgroundColor = RGB(40, 76, 112);
    [self.view addSubview:line];
    
    UIButton *downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downBtn.frame = CGRectMake(KScreenWidth-74, 123, 44, 44);
    [self.view addSubview:downBtn];
    [downBtn setImage:[UIImage imageNamed:@"down_arrow"] forState:0];
    [downBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setAPPLanguage:(NSString *)language{
    [DAConfig setUserLanguage:language];
    
    
    UITabBarController *tbc = [[TabbarController alloc]init];
    // 跳转到个人中心页面（即设置语言的那个tabBarItem）
    tbc.selectedIndex = self.tabBarController.selectedIndex;
    
    // 创建设置页面
    SettingViewController *settingVC = [[SettingViewController alloc]init];
    settingVC.hidesBottomBarWhenPushed = YES;
    
    // 创建语言选择界面
    LanguageViewController *languageVC = [[LanguageViewController alloc]init];
    languageVC.hidesBottomBarWhenPushed = YES;
    
    UINavigationController *nvc = tbc.selectedViewController;
    
    // 备用
    NSMutableArray *vcs = nvc.viewControllers.mutableCopy;
    [vcs addObjectsFromArray:@[languageVC]];
    
    //解决奇怪的动画bug。异步执行
    dispatch_async(dispatch_get_main_queue(), ^{
        
        //注意刷新rootViewController的时机，在主线程异步执行
        //先刷新rootViewController
        [UIApplication sharedApplication].delegate.window.rootViewController = tbc;
        
        //然后再给个人中心的nvc设置viewControllers
        nvc.viewControllers = vcs;
    });

}

-(void)btnClick{
    __weak typeof(self) weakSelf=self;
    if (!_arrowView) {
        _arrowView = [[ArrowView alloc]initWithFrame:CGRectMake(30, 172, KScreenWidth-60, 108)];
        _arrowView.layer.shadowOpacity = 0.5;          // 阴影透明度（0~1）
        _arrowView.layer.shadowColor = [UIColor blackColor].CGColor; // 阴影颜色
        _arrowView.layer.shadowRadius = 3;             // 阴影扩散范围（值越大越模糊）
        _arrowView.layer.shadowOffset = CGSizeMake(0, 0); // 阴影偏移（0,0表示四周均匀）
        _arrowView.layer.masksToBounds = NO;
        _arrowView.clipsToBounds = NO;
        _arrowView.callBack = ^(NSString * _Nonnull lang) {
            if (![lang isEqualToString:weakSelf.languageLabel.text]) {
                if ([lang isEqualToString:@"zh"]) {
                    [weakSelf setAPPLanguage:@"zh-Hans"];
                }else{
                    [weakSelf setAPPLanguage:@"en"];
                }
                weakSelf.languageLabel.text = lang;
            }
            [UIView animateWithDuration:0.3 animations:^{
                weakSelf.arrowView.alpha = 0;
            } completion:^(BOOL finished) {
                [weakSelf.arrowView removeFromSuperview];
                weakSelf.arrowView = nil;
            }];
        };
        [self.view addSubview:_arrowView];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.arrowView.alpha = 0;
        } completion:^(BOOL finished) {
           [weakSelf.arrowView removeFromSuperview];
           weakSelf.arrowView = nil;
        }];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    if (self.arrowView) {
        // 判断触摸点是否在目标视图外部
        if (!CGRectContainsPoint(self.arrowView.frame, point)) {
            [UIView animateWithDuration:0.3 animations:^{
                self.arrowView.alpha = 0;
            } completion:^(BOOL finished) {
               [self.arrowView removeFromSuperview];
                self.arrowView = nil;
            }];
        }
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
